package com.only.common.util;


import cn.hutool.core.collection.CollectionUtil;
import com.only.common.doucment.Either;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author only
 * @date 2024/1/4
 * @description
 */
public class FutureUtil {
    @SafeVarargs
    public static Either<Exception, FutureResult> yield(Supplier<Object>... suppliers) {
        return FutureUtil.yield(Arrays.stream(suppliers).collect(Collectors.toList()));
    }

    public static Either<Exception, FutureResult> yield(List<Supplier<Object>> suppliers) {
        return FutureUtil.yield(suppliers, Optional.empty());
    }

    public static Either<Exception, FutureResult> yield(List<Supplier<Object>> suppliers, Executor executor) {
        return FutureUtil.yield(suppliers, Optional.ofNullable(executor));
    }

    public static Either<Exception, FutureResult> yield(List<Supplier<Object>> suppliers, Optional<Executor> executorOpt) {
        List<CompletableFuture<Object>> futures = new ArrayList<>();

        if (CollectionUtil.isEmpty(suppliers)) {
            return Either.right(new FutureResult(new ArrayList<>()));
        }

        for (Supplier<Object> supplier : suppliers) {
            if (executorOpt.isPresent()) {
                futures.add(CompletableFuture.supplyAsync(supplier, executorOpt.get()));
            } else {
                futures.add(CompletableFuture.supplyAsync(supplier));
            }
        }

        try {
            List<Object> ret = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
            return Either.right(new FutureResult(ret));
        } catch (Exception ex) {
            return Either.left(ex);
        }
    }

    public static class FutureResult {
        private List<Object> ret;

        public FutureResult(List<Object> ret) {
            this.ret = ret;
        }

        public <T> T get(int idx) {
            return (T) ret.get(idx);
        }
    }


    public static void main(String[] args) {
        List<Supplier<Object>> suppliers = new LinkedList<>();
        suppliers.add(()-> new String("hello"));
        suppliers.add(()-> new Integer(1));
        suppliers.add(()-> new Double(1.1));

        Either<Exception, FutureResult> either = FutureUtil.yield(suppliers);
        boolean left = either.isLeft();
        boolean right = either.isRight();
        FutureResult futureResult = either.get();
        for (int i = 0; i < suppliers.size(); i++) {
            Object o = futureResult.get(i);
            System.out.println(o);
        }
    }
}
